package com.genesis.yunnanji.widget;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;

import com.genesis.yunnanji.R;
import com.genesis.yunnanji.StoreApplication;
import com.genesis.yunnanji.bean.CityInfo;
import com.genesis.yunnanji.utils.GetJsonDataUtil;
import com.genesis.yunnanji.utils.ResourceUtil;
import com.google.gson.Gson;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

/**
 * 城市、时间选择器
 */
public class PickerViewUtil {
    private static PickerViewUtil pickerViewUtil;
    private TimePickerView timePickerView;

    private PickerViewUtil() {
    }

    public static PickerViewUtil getInstance() {
        if (pickerViewUtil == null) {
            synchronized (PickerViewUtil.class) {
                if (pickerViewUtil == null) {
                    pickerViewUtil = new PickerViewUtil();
                }
            }
        }
        return pickerViewUtil;
    }

    public void showLinkPicker(Context mContext, final ArrayList<String> options1Items, final ArrayList<ArrayList<String>> options2Items) {
        if (options1Items == null || options2Items == null || options1Items.size() == 0 || options2Items.size() == 0) {
            return;
        }
        OptionsPickerView pvOptions = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String link1 = options1Items.get(options1);
                String link2 = options2Items.get(options1).get(options2);
                if (onLinkCompleteListener != null) {
                    onLinkCompleteListener.onSelectLink(link1, link2);
                }
            }
        })
                .setLineSpacingMultiplier(2.0f)
                .setSubmitText(ResourceUtil.getString(mContext, R.string.complete))
                .setSubmitColor(ResourceUtil.getColor(mContext, R.color.colorTheme))
                .setCancelColor(ResourceUtil.getColor(mContext, R.color.color_999))
                .setTitleBgColor(ResourceUtil.getColor(mContext, R.color.color_fff))
                .isCenterLabel(false)
                .build();
        pvOptions.setPicker(options1Items, options2Items);//二级选择器
        pvOptions.setSelectOptions(options1Items.size() / 2, options2Items.get(options1Items.size() / 2).size() / 2);
        pvOptions.show();
    }

    public void showDatePicker(Context mContext) {
        Calendar selectedDate = Calendar.getInstance();
        selectedDate.set(1990, 5, 15);
        Calendar startDate = Calendar.getInstance();
        startDate.set(1900, 0, 1);
        Calendar endDate = Calendar.getInstance();
        endDate.set(endDate.get(Calendar.YEAR), endDate.get(Calendar.MONTH), endDate.get(Calendar.DATE));
        //时间选择器 ，自定义布局
        timePickerView = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                if (onTimeCompleteListener != null) {
                    onTimeCompleteListener.onSelectDate(date);
                }
            }
        }).setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.popup_date_picker, new CustomListener() {
                    @Override
                    public void customLayout(final View v) {
                        TextView tvComplete = v.findViewById(R.id.tv_complete);
                        TextView tvCancel = v.findViewById(R.id.tv_cancel);
                        tvComplete.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                timePickerView.returnData();
                                timePickerView.dismiss();
                            }
                        });
                        tvCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                timePickerView.dismiss();
                            }
                        });
                        //公农历切换
                        CheckBox cb_lunar = v.findViewById(R.id.cb_lunar);
                        cb_lunar.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                            @Override
                            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                                timePickerView.setLunarCalendar(!timePickerView.isLunarCalendar());
                                ViewGroup timePicker = v.findViewById(R.id.timepicker);
                                View year = timePicker.getChildAt(0);
                                LinearLayout.LayoutParams lp = ((LinearLayout.LayoutParams) year.getLayoutParams());
                                lp.weight = isChecked ? 0.8f : 1f;
                                year.setLayoutParams(lp);
                                for (int i = 1; i < timePicker.getChildCount(); i++) {
                                    View childAt = timePicker.getChildAt(i);
                                    LinearLayout.LayoutParams childLp = ((LinearLayout.LayoutParams) childAt.getLayoutParams());
                                    childLp.weight = isChecked ? 1f : 1.1f;
                                    childAt.setLayoutParams(childLp);
                                }
                            }
                        });
                    }
                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLineSpacingMultiplier(2.0f)
                .isCenterLabel(false)
                .build();
        timePickerView.show();
    }

    public void showCityPicker(Context mContext) {// 弹出城市选择器
        initJsonData();
        OptionsPickerView pvOptions = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String province = options1CityItems.get(options1).getPickerViewText();
                String city = options2CityItems.get(options1).get(options2);
                //String area = options3CityItems.get(options1).get(options2).get(options3).;
                if (onCityCompleteListener != null) {
                    onCityCompleteListener.onSelectCity(province, city, "");
                }
            }
        })
                .setLineSpacingMultiplier(2.0f)
                .setSubmitText(ResourceUtil.getString(mContext, R.string.complete))
                .setSubmitColor(ResourceUtil.getColor(mContext, R.color.colorTheme))
                .setCancelColor(ResourceUtil.getColor(mContext, R.color.color_999))
                .setTitleBgColor(ResourceUtil.getColor(mContext, R.color.color_fff))
                .isCenterLabel(false)
                .build();
        pvOptions.setPicker(options1CityItems, options2CityItems);//二级选择器
        pvOptions.setSelectOptions(5, 5);
        pvOptions.show();
    }

    private void initJsonData() {//解析数据
        String JsonData = new GetJsonDataUtil().getJson(StoreApplication.getInstance(), "province.json");//获取assets目录下的json文件数据
        ArrayList<CityInfo> jsonBean = parseData(JsonData);//用Gson 转成实体
        options1CityItems = jsonBean;
        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                if (CityName.equals("北京市") || CityName.equals("天津市") || CityName.equals("上海市") || CityName.equals("重庆市")) {
                    CityList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                } else {
                    CityList.add(CityName);//添加城市
                }
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }
            options2CityItems.add(CityList);
            options3CityItems.add(Province_AreaList);
        }
    }

    private ArrayList<CityInfo> options1CityItems = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2CityItems = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3CityItems = new ArrayList<>();

    private ArrayList<CityInfo> parseData(String result) {//Gson 解析
        ArrayList<CityInfo> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                CityInfo entity = gson.fromJson(data.optJSONObject(i).toString(), CityInfo.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }

    private OnTimeCompleteListener onTimeCompleteListener;

    public void setOnTimeCompleteListener(OnTimeCompleteListener onTimeCompleteListener) {
        this.onTimeCompleteListener = onTimeCompleteListener;
    }

    public interface OnTimeCompleteListener {
        void onSelectDate(Date date);
    }


    private OnCityCompleteListener onCityCompleteListener;

    public void setOnCityCompleteListener(OnCityCompleteListener onCityCompleteListener) {
        this.onCityCompleteListener = onCityCompleteListener;
    }

    public interface OnCityCompleteListener {
        void onSelectCity(String province, String city, String area);
    }

    private OnLinkCompleteListener onLinkCompleteListener;

    public void setOnLinkCompleteListener(OnLinkCompleteListener onLinkCompleteListener) {
        this.onLinkCompleteListener = onLinkCompleteListener;
    }

    public interface OnLinkCompleteListener {
        void onSelectLink(String link1, String link2);
    }
}
